#!/bin/sh

if [ -z $1 ] || [ -z $2 ]; then
    echo -e "Usage:$0 [slave ip] [mysql root password]"
    exit 1
fi

echo -e "This script will help you to install Auto Backup Script on both machine"
echo -e "You should run this script on main machine,not slave machine!"
echo -e "Press Enter"
read
while [ ! -f $HOME/.ssh/id_rsa.pub ]; do
    echo -e "Your local identification is not found and will be created"
    echo -e "Just press Enter three times and DO NOT use any passwd!"
    echo -e "Press Enter"
    read
    ssh-keygen -t rsa
done

echo -e "Will transfer identification file to slave machine,input remote root password if needed!"
cat $HOME/.ssh/id_rsa.pub | ssh root@$1 'test -d .ssh || mkdir .ssh;  cat >>.ssh/authorized_keys; restorecon -R -v /root/.ssh/'
if [ $? -ne 0 ]; then
    echo "Fail and that's all I know,byebye!"
    exit 1
fi

if [ ! -f /root/backupall.sh ]; then
    echo -e "I can not found the backupall script,byebye!"
    exit 1
fi

echo -e "Will add backup script to cron task...\c"
chmod a+x /root/backupall.sh
sed -i "s/SlaveIp=''/SlaveIp='$1'/g" /root/backupall.sh
sed -i "s/MySqlRootPassword=''/MySqlRootPassword='$2'/g" /root/backupall.sh
ln -sf /root/backupall.sh /etc/cron.hourly/
echo "Done!"
echo -e "Do init backup..."
./backupall.sh
if [ $? -ne 0 ]; then
    echo "Fail and that's all I know,byebye!"
    exit 1
else
    echo "All well done!"
fi
